package web.eshop.panels;

import domain.shop.Product;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import service.facade.customer.ShopCustomerService;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Panel with ladder representing favourite products and the most searched phrase
 */
public final class LadderPanel extends ShopBasePanel {

    /**
     * How many products should be represent.
     */
    private static final int AMOUNT_OF_PRODUCTS = 5;
    @SpringBean
    private ShopCustomerService shopCustomerService;
    private final IModel<List<Product>> topProductsModel;

    public LadderPanel(String id) {
        super(id);
        topProductsModel = loadRelatedProductModel(AMOUNT_OF_PRODUCTS);
        showRelatedProducts(topProductsModel);
    }

    private void showRelatedProducts(IModel<List<Product>> productMethodModel) {
        add(new ListView<Product>("productList", productMethodModel) {

            @Override
            protected void populateItem(final ListItem<Product> item) {
                item.add(new ProductPanel("showProductPanel", item));
            }
        });

    }

    private LoadableDetachableModel<List<Product>> loadRelatedProductModel(final int amoutOfProducts) {
        return new LoadableDetachableModel<List<Product>>() {

            @Override
            protected List<Product> load() {
                ArrayList arrayList = new ArrayList(
                        shopCustomerService.findTopFavouriteProducts(amoutOfProducts));

                Collections.sort(arrayList);
                return arrayList;
            }
        };
    }
}
